<?php

namespace common\observer;

use common\model\TaskModel;
use common\service\TaskGenerateService;
use support\SingletonTrait;
use common\service\CommonService;
use Throwable;
use teamones\dbeventObserver\interfaces\SplSubject;
use teamones\dbeventObserver\interfaces\SplObserver;

/**
 * 实体属性更新 同步到任务
 */
class EntityAttributeChangeSyncToTask implements SplObserver
{
    use SingletonTrait;

    public $syncFields = [
        'is_append',
        'code',
        'initial_episode_code',
        'showings_number',
    ];
    protected $orderFields = [
        'code',
        'initial_episode_code',
        'showings_number',
    ];

    protected $syncModuleCode = [
        'level',
        'asset',
        'shot',
        'design',
    ];

    /**
     * @param SplSubject $subject
     * @return void
     */
    function update(SplSubject $subject): void
    {
        $entity = $subject->getSubjectData();
        $updateData = $subject->getSplUpdateData();

        $module = module_by_id($entity['module_id']);
        if (!in_array($module['code'], $this->syncModuleCode)) {
            return;
        }

        // 求出变化的字段和要同步的字段的交集
        $changedFieldIntersect = array_intersect($this->syncFields, array_keys($updateData));
        if (empty($changedFieldIntersect)) {
            return;
        }
        // 查询任务
        $taskList = model(TaskModel::class)->field('id,json')->where(['entity_id' => $entity['id']])->select();

        // 组装要更新的字段
        $syncData = [];
        $orderFieldsFilled = false;
        foreach ($changedFieldIntersect as $updateKey) {
            if (in_array($updateKey, $this->orderFields) && !$orderFieldsFilled) {
                if (in_array($entity['module_id'], TaskGenerateService::getInstance()->assetModuleIdList)) {
                    $syncData['order_str'] = $entity['code'];
                } else {
                    $syncData['order_str'] = sprintf("%s/%s/%s", $entity['initial_episode_code'], $entity['showings_number'], $entity['code']);
                }
                $orderFieldsFilled = true;
            } else {
                $syncData['task_' . $updateKey] = $updateData[$updateKey];
            }
        }
        foreach ($taskList as $task) {
            $tmpSyncData = $syncData;
            $tmpSyncData['id'] = $task['id'];
            try {
                // 预设好当前模块
                request()->getModuleCode('task');
                CommonService::instance('task')
                    ->setCurrentModuleCode('task')
                    ->update($tmpSyncData, 'task', false);
            } catch (Throwable $e) {
                trace(format_exception_info($e), 'ERR');
            }
        }
    }
}
